package org.zwy.gradetrack.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.zwy.gradetrack.entity.GraduateRequirementAchievement;
import org.zwy.gradetrack.service.GraduateRequirementAchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/graduate-requirement-achievement")
public class GraduateRequirementAchievementController {

    @Autowired
    private GraduateRequirementAchievementService achievementService;

    @PostMapping
    public Result<?> save(@RequestBody GraduateRequirementAchievement achievement) {
        achievement.setCreateTime(LocalDateTime.now());
        achievement.setUpdateTime(LocalDateTime.now());
        achievementService.calculateComprehensiveScore(achievement);
        achievementService.save(achievement);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody GraduateRequirementAchievement achievement) {
        achievement.setUpdateTime(LocalDateTime.now());
        achievementService.calculateComprehensiveScore(achievement);
        achievementService.updateById(achievement);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        achievementService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(achievementService.getById(id));
    }

    @GetMapping("/page")
    public Result<?> page(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(required = false) String graduateId,
                         @RequestParam(required = false) Integer requirementId,
                         @RequestParam(required = false) Integer evaluationYear) {
        LambdaQueryWrapper<GraduateRequirementAchievement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(graduateId != null, GraduateRequirementAchievement::getGraduateId, graduateId)
               .eq(requirementId != null, GraduateRequirementAchievement::getRequirementId, requirementId)
               .eq(evaluationYear != null, GraduateRequirementAchievement::getEvaluationYear, evaluationYear)
               .orderByDesc(GraduateRequirementAchievement::getCreateTime);
        
        Page<GraduateRequirementAchievement> page = achievementService.page(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(page);
    }
} 